﻿// ------------------------------------------------------------------------
//    YATSE - A touch screen remote controller for XBMC (.NET 3.5)
//    Copyright (C) 2010  Tolriq (http://code.google.com/p/yatse/)
//
//    This program is free software: you can redistribute it and/or modify
//    it under the terms of the GNU General Public License as published by
//    the Free Software Foundation, either version 3 of the License, or
//    (at your option) any later version.
//
//    This program is distributed in the hope that it will be useful,
//    but WITHOUT ANY WARRANTY; without even the implied warranty of
//    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//    GNU General Public License for more details.
//
//    You should have received a copy of the GNU General Public License
//    along with this program.  If not, see <http://www.gnu.org/licenses/>.
// ------------------------------------------------------------------------

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Runtime.InteropServices;
using System.Windows;
using System.Linq;
using System.Windows.Automation.Peers;
using System.Windows.Controls;
using System.Windows.Forms;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Media.Imaging;
using System.Windows.Threading;
using System.Xml.Serialization;
using FluidKit.Controls;
using Microsoft.Win32;
using XBMC;
using YATSE.Libs;
using Application = System.Windows.Forms.Application;
using ListBox = System.Windows.Controls.ListBox;
using MessageBox = System.Windows.Forms.MessageBox;

namespace YATSE
{
    public partial class YatseWindow
    {
        private Grid _currentGrid;
        private bool _isScreenSaver;
        private int _currentlyPlaying;
        private long _timer;
        private const int TimerScreenSaver = 120;
        private int _diaporamaCurrentImage;
        private XbmcCommunicator _xbmc;
        private readonly GenreCollection _genreDataSource;
        private readonly FilmCollection _filmDataSource;
        private readonly AlbumCollection _albumDataSource;
        private readonly ShowCollection _showDataSource;
        private readonly EpisodeCollection _episodeDataSource;

        private bool _isLibraryRefresh;

        private bool _keyShift;
        private bool _isMouseDown;
        private Point _mouseDownPoint;
        private Point _mouseDownPreviousPoint;
        private DateTime _mouseDownTime;
        private DateTime _mouseDownPreviousTime;
        private DateTime _mouseClickTime;
        private int _mouseClickItemNewIndex;
        private int _mouseClickItemIndex;

        private readonly string _currentSkin = "Default";
        private readonly string _logFile = Application.StartupPath + @"\Log\Yatse.log";
        private readonly string _configFile = Application.StartupPath + @"\Settings.xml";

        private readonly XmlLang _lang = new XmlLang();
        private YatseConfig _config = new YatseConfig();

        [DllImport("user32.dll")]
        static extern bool SetForegroundWindow(IntPtr hWnd);


        private static void RebootOS()
        {
            Process.Start("shutdown.exe", "-r -t 00");
        }

        private static void ShutdownOS()
        {
            Process.Start("shutdown.exe", "-s -t 00");
        }

        private void RotateLog()
        {
            if (!_config.Debug) return;
            try
            {
                File.Delete(_logFile + ".old");
                File.Delete(Application.StartupPath + @"\Log\Yatse-Remote.log.old");
                File.Move(_logFile, _logFile + ".old");
                File.Move(Application.StartupPath + @"\Log\Yatse-Remote.log", Application.StartupPath + @"\Log\Yatse-Remote.log.old");
            }
            catch (Exception) { }
        }

        private void WriteToLog(string message)
        {
            if (!_config.Debug) return;
            try
            {
                var sw = new StreamWriter(_logFile, true);
                sw.WriteLine(DateTime.Now + " : " + message);
                sw.Flush();
                sw.Close();
            }
            catch (Exception) {}
        }

        private void DumpToLog(object message)
        {
            if (!_config.Debug) return;
            try
            {
                var s = new XmlSerializer(message.GetType());
                var sw = new StringWriter();
                s.Serialize(sw, message);
                var message2 = sw.ToString().Replace("<?xml version=\"1.0\" encoding=\"utf-16\"?>\r\n","").Replace(" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\"","");
                var sw2 = new StreamWriter(_logFile, true);
                sw2.WriteLine(message2);
                sw2.Flush();
                sw2.Close();
            }
            catch (Exception) { }
        }

        private void LoadConfig(string configFile)
        {
            YatseConfig config;
            try
            {
                var deserializer = new XmlSerializer(typeof (YatseConfig));
                TextReader textReader = new StreamReader(configFile);
                config = (YatseConfig)deserializer.Deserialize(textReader);
                textReader.Close();
            }
            catch (Exception)
            {
                return;
            }
            _config = config;
            return;
        }

        private void SaveConfig(string configFile)
        {
            try
            {
                var serializer = new XmlSerializer(typeof (YatseConfig));
                TextWriter textWriter = new StreamWriter(configFile);
                serializer.Serialize(textWriter, _config);
                textWriter.Close();
            }
            catch (Exception) { }
            return;
        }


        private void Change_Display_Settings(object sender, EventArgs e)
        {
            Topmost = _config.TopMost;
            WindowStartupLocation = WindowStartupLocation.Manual;
            Activate();
            var dx = 1.0;
            var dy = 1.0;
            if (PresentationSource.FromVisual(this) != null)
            {
                var m = PresentationSource.FromVisual(this).CompositionTarget.TransformToDevice;
                dx = m.M11;
                dy = m.M22;
            }
            var screens = Screen.AllScreens;
            if (screens.Length == 1 || !_config.SecondScreen)
            {
                if (_config.ForceResolution)
                {
                    var screenRes = new ScreenResolution();
                    var currentRes = screenRes.GetDevmode(0, -1);
                    WriteToLog("CurrentResolutionMonoScreen");
                    DumpToLog(currentRes);
                    if (currentRes.dmPelsHeight != _config.Resolution.dmPelsHeight || currentRes.dmPelsWidth != _config.Resolution.dmPelsWidth || currentRes.dmBitsPerPel != _config.Resolution.dmBitsPerPel)
                    {
                        screenRes.ChangeResolutionMode(0, _config.Resolution);
                        WriteToLog("ChangeResolutionMonoScreen");
                        DumpToLog(_config.Resolution);
                    }
                }
                Top = 0;
                Left = 0;
            }
            else
            {
                if (_config.ForceResolution)
                {
                    var screenRes = new ScreenResolution();
                    var currentRes = screenRes.GetDevmode(1, -1);
                    WriteToLog("CurrentResolutionMultiScreen");
                    DumpToLog(currentRes);
                    if (currentRes.dmPelsHeight != _config.Resolution.dmPelsHeight || currentRes.dmPelsWidth != _config.Resolution.dmPelsWidth || currentRes.dmBitsPerPel != _config.Resolution.dmBitsPerPel)
                    {
                        screenRes.ChangeResolutionMode(1, _config.Resolution);
                        WriteToLog("ChangeResolutionMultiScreen");
                        DumpToLog(_config.Resolution);
                    }
                }
                System.Threading.Thread.Sleep(350);
                screens = Screen.AllScreens;
                foreach (var scr in screens.Where(scr => !scr.Primary))
                {
                    Top = scr.Bounds.Top / dy ;
                    Left = scr.Bounds.Left / dx;
                    break;
                }
            }
            if (_config.Resolution.dmPelsWidth > 0)
            {
                Width = _config.Resolution.dmPelsWidth / dx;
                Height = _config.Resolution.dmPelsHeight / dy;
            }
            img_Current_Music_Image.Width = img_Current_Music_Image.ActualHeight;
        }
                
        private void LoadSkin()
        {
            try
            {
                var imgVideo = new ImageBrush
                                   {
                                       ImageSource =
                                           new BitmapImage(
                                           new Uri(@"Skin\" + _currentSkin + @"\Interface\Menu_Video.png",
                                                   UriKind.Relative))
                                   };
                var imgMusic = new ImageBrush
                                   {
                                       ImageSource =
                                           new BitmapImage(
                                           new Uri(@"Skin\" + _currentSkin + @"\Interface\Menu_Music.png",
                                                   UriKind.Relative))
                                   };
                var imgCurrent = new ImageBrush
                                     {
                                         ImageSource =
                                             new BitmapImage(
                                             new Uri(@"Skin\" + _currentSkin + @"\Interface\Menu_Current.png",
                                                     UriKind.Relative))
                                     };
                var imgRemote = new ImageBrush
                                    {
                                        ImageSource =
                                            new BitmapImage(
                                            new Uri(@"Skin\" + _currentSkin + @"\Interface\Menu_Remote.png",
                                                    UriKind.Relative))
                                    };
                var imgSettings = new ImageBrush
                                      {
                                          ImageSource =
                                              new BitmapImage(
                                              new Uri(@"Skin\" + _currentSkin + @"\Interface\Menu_Settings.png",
                                                      UriKind.Relative))
                                      };
                var imgClose = new ImageBrush
                                   {
                                       ImageSource =
                                           new BitmapImage(
                                           new Uri(@"Skin\" + _currentSkin + @"\Interface\Menu_Close.png",
                                                   UriKind.Relative))
                                   };
                var imgBackground = new ImageBrush
                                        {
                                            ImageSource =
                                                new BitmapImage(
                                                new Uri(@"Skin\" + _currentSkin + @"\Interface\Background.png",
                                                        UriKind.Relative))
                                        };
                var imgPrevious = new ImageBrush
                                      {
                                          ImageSource =
                                              new BitmapImage(
                                              new Uri(@"Skin\" + _currentSkin + @"\Interface\Remote_Previous.png",
                                                      UriKind.Relative))
                                      };
                var imgRewind = new ImageBrush
                                    {
                                        ImageSource =
                                            new BitmapImage(
                                            new Uri(@"Skin\" + _currentSkin + @"\Interface\Remote_Rewind.png",
                                                    UriKind.Relative))
                                    };
                var imgPlay = new ImageBrush
                                  {
                                      ImageSource =
                                          new BitmapImage(
                                          new Uri(@"Skin\" + _currentSkin + @"\Interface\Remote_Play.png",
                                                  UriKind.Relative))
                                  };
                var imgPause = new ImageBrush
                                   {
                                       ImageSource =
                                           new BitmapImage(
                                           new Uri(@"Skin\" + _currentSkin + @"\Interface\Remote_Pause.png",
                                                   UriKind.Relative))
                                   };
                var imgStop = new ImageBrush
                                  {
                                      ImageSource =
                                          new BitmapImage(
                                          new Uri(@"Skin\" + _currentSkin + @"\Interface\Remote_Stop.png",
                                                  UriKind.Relative))
                                  };
                var imgForward = new ImageBrush
                                     {
                                         ImageSource =
                                             new BitmapImage(
                                             new Uri(@"Skin\" + _currentSkin + @"\Interface\Remote_Forward.png",
                                                     UriKind.Relative))
                                     };
                var imgNext = new ImageBrush
                                  {
                                      ImageSource =
                                          new BitmapImage(
                                          new Uri(@"Skin\" + _currentSkin + @"\Interface\Remote_Next.png",
                                                  UriKind.Relative))
                                  };
                var imgKey = new ImageBrush
                                   {
                                       ImageSource =
                                           new BitmapImage(
                                           new Uri(@"Skin\" + _currentSkin + @"\Interface\Keyboard_Key.png",
                                                   UriKind.Relative))
                                   };
                var imgVolDown = new ImageBrush
                                     {
                                         ImageSource =
                                             new BitmapImage(
                                             new Uri(@"Skin\" + _currentSkin + @"\Interface\Vol_Down.png",
                                                     UriKind.Relative))
                                     };
                var imgVolMute = new ImageBrush
                                     {
                                         ImageSource =
                                             new BitmapImage(
                                             new Uri(@"Skin\" + _currentSkin + @"\Interface\Vol_Mute.png",
                                                     UriKind.Relative))
                                     };
                var imgVolUp = new ImageBrush
                                   {
                                       ImageSource =
                                           new BitmapImage(new Uri(@"Skin\" + _currentSkin + @"\Interface\Vol_Up.png",
                                                                   UriKind.Relative))
                                   };

                var imgLeft = new ImageBrush
                                  {
                                      ImageSource =
                                          new BitmapImage(
                                          new Uri(@"Skin\" + _currentSkin + @"\Interface\Remote_Left.png",
                                                  UriKind.Relative))
                                  };
                var imgRight = new ImageBrush
                                   {
                                       ImageSource =
                                           new BitmapImage(
                                           new Uri(@"Skin\" + _currentSkin + @"\Interface\Remote_Right.png",
                                                   UriKind.Relative))
                                   };
                var imgUp = new ImageBrush
                                {
                                    ImageSource =
                                        new BitmapImage(new Uri(@"Skin\" + _currentSkin + @"\Interface\Remote_Up.png",
                                                                UriKind.Relative))
                                };
                var imgDown = new ImageBrush
                                  {
                                      ImageSource =
                                          new BitmapImage(
                                          new Uri(@"Skin\" + _currentSkin + @"\Interface\Remote_Down.png",
                                                  UriKind.Relative))
                                  };
                var imgEnter = new ImageBrush
                                   {
                                       ImageSource =
                                           new BitmapImage(
                                           new Uri(@"Skin\" + _currentSkin + @"\Interface\Remote_Enter.png",
                                                   UriKind.Relative))
                                   };
                var imgInfo = new ImageBrush
                                  {
                                      ImageSource =
                                          new BitmapImage(
                                          new Uri(@"Skin\" + _currentSkin + @"\Interface\Remote_Info.png",
                                                  UriKind.Relative))
                                  };
                var imgReturn = new ImageBrush
                                    {
                                        ImageSource =
                                            new BitmapImage(
                                            new Uri(@"Skin\" + _currentSkin + @"\Interface\Remote_Return.png",
                                                    UriKind.Relative))
                                    };
                var imgPlayCd = new ImageBrush
                                    {
                                        ImageSource =
                                            new BitmapImage(
                                            new Uri(@"Skin\" + _currentSkin + @"\Interface\Remote_PlayCD.png",
                                                    UriKind.Relative))
                                    };
                var imgEject = new ImageBrush
                                   {
                                       ImageSource =
                                           new BitmapImage(
                                           new Uri(@"Skin\" + _currentSkin + @"\Interface\Remote_Eject.png",
                                                   UriKind.Relative))
                                   };
                var imgActions = new ImageBrush
                {
                    ImageSource =
                        new BitmapImage(
                        new Uri(@"Skin\" + _currentSkin + @"\Interface\Menu_Actions.png",
                                UriKind.Relative))
                };

                var imgTv = new ImageBrush
                {
                    ImageSource =
                        new BitmapImage(
                        new Uri(@"Skin\" + _currentSkin + @"\Interface\Menu_TV.png",
                                UriKind.Relative))
                };

                var imgRebootLocal = new ImageBrush
                {
                    ImageSource =
                        new BitmapImage(
                        new Uri(@"Skin\" + _currentSkin + @"\Interface\Menu_Restart_Local.png",
                                UriKind.Relative))
                };

                var imgRebootXBMC = new ImageBrush
                {
                    ImageSource =
                        new BitmapImage(
                        new Uri(@"Skin\" + _currentSkin + @"\Interface\Menu_Restart_XBMC.png",
                                UriKind.Relative))
                };

                var imgShutdownLocal = new ImageBrush
                {
                    ImageSource =
                        new BitmapImage(
                        new Uri(@"Skin\" + _currentSkin + @"\Interface\Menu_Shutdown_Local.png",
                                UriKind.Relative))
                };

                var imgShutdownXBMC = new ImageBrush
                {
                    ImageSource =
                        new BitmapImage(
                        new Uri(@"Skin\" + _currentSkin + @"\Interface\Menu_Shutdown_XBMC.png",
                                UriKind.Relative))
                };

                var imgWolXBMC = new ImageBrush
                {
                    ImageSource =
                        new BitmapImage(
                        new Uri(@"Skin\" + _currentSkin + @"\Interface\Menu_WOL.png",
                                UriKind.Relative))
                };

                var imgCaps= new ImageBrush
                {
                    ImageSource =
                        new BitmapImage(
                        new Uri(@"Skin\" + _currentSkin + @"\Interface\Caps.png",
                                UriKind.Relative))
                };


                btn_Video.Background = imgVideo;
                btn_Music.Background = imgMusic;
                btn_Current.Background = imgCurrent;
                btn_Remote.Background = imgRemote;
                btn_Actions_Settings.Background = imgSettings;
                btn_Actions_Close.Background = imgClose;
                btn_Actions.Background = imgActions;
                btn_TV.Background = imgTv;
                btn_Actions_Reboot_Local.Background = imgRebootLocal;
                btn_Actions_Reboot_XBMC.Background = imgRebootXBMC;
                btn_Actions_Shutdown_Local.Background = imgShutdownLocal;
                btn_Actions_Shutdown_XBMC.Background = imgShutdownXBMC;
                btn_Actions_WOL_XBMC.Background = imgWolXBMC;

                Main_Grid.Background = imgBackground;
                btn_Current_Previous.Background = imgPrevious;
                btn_Current_Rewind.Background = imgRewind;
                btn_Current_Play.Background = imgPlay;
                btn_Current_Pause.Background = imgPause;
                btn_Current_Stop.Background = imgStop;
                btn_Current_Forward.Background = imgForward;
                btn_Current_Next.Background = imgNext;
                btn_Current_VolDown.Background = imgVolDown;
                btn_Current_VolMute.Background = imgVolMute;
                btn_Current_VolUp.Background = imgVolUp;
                btn_Volume_Mute.Background = imgVolMute;

                btn_Remote_Previous.Background = imgPrevious;//2
                btn_Remote_Play.Background = imgPlay;
                btn_Remote_Pause.Background = imgPause;
                btn_Remote_Stop.Background = imgStop;
                btn_Remote_Next.Background = imgNext;//2
                btn_Remote_VolDown.Background = imgVolDown;
                btn_Remote_VolMute.Background = imgVolMute;
                btn_Remote_VolUp.Background = imgVolUp;

                btn_Remote_Up.Background = imgUp;
                btn_Remote_Down.Background = imgDown;
                btn_Remote_Left.Background = imgLeft;
                btn_Remote_Right.Background = imgRight;
                btn_Remote_Enter.Background = imgEnter;
                btn_Remote_Info.Background = imgInfo;
                btn_Remote_Return.Background = imgReturn;
                btn_Remote_PlayCD.Background = imgPlayCd;
                btn_Remote_Eject.Background = imgEject;

                btn_Remote_Key_A.Background = imgKey;
                btn_Remote_Key_B.Background = imgKey;
                btn_Remote_Key_C.Background = imgKey;
                btn_Remote_Key_D.Background = imgKey;
                btn_Remote_Key_E.Background = imgKey;
                btn_Remote_Key_F.Background = imgKey;
                btn_Remote_Key_G.Background = imgKey;
                btn_Remote_Key_H.Background = imgKey;
                btn_Remote_Key_I.Background = imgKey;
                btn_Remote_Key_J.Background = imgKey;
                btn_Remote_Key_K.Background = imgKey;
                btn_Remote_Key_L.Background = imgKey;
                btn_Remote_Key_M.Background = imgKey;
                btn_Remote_Key_N.Background = imgKey;
                btn_Remote_Key_O.Background = imgKey;
                btn_Remote_Key_P.Background = imgKey;
                btn_Remote_Key_Q.Background = imgKey;
                btn_Remote_Key_R.Background = imgKey;
                btn_Remote_Key_S.Background = imgKey;
                btn_Remote_Key_T.Background = imgKey;
                btn_Remote_Key_U.Background = imgKey;
                btn_Remote_Key_V.Background = imgKey;
                btn_Remote_Key_W.Background = imgKey;
                btn_Remote_Key_X.Background = imgKey;
                btn_Remote_Key_Y.Background = imgKey;
                btn_Remote_Key_Z.Background = imgKey;
                btn_Remote_Key_0.Background = imgKey;
                btn_Remote_Key_1.Background = imgKey;
                btn_Remote_Key_2.Background = imgKey;
                btn_Remote_Key_3.Background = imgKey;
                btn_Remote_Key_4.Background = imgKey;
                btn_Remote_Key_5.Background = imgKey;
                btn_Remote_Key_6.Background = imgKey;
                btn_Remote_Key_7.Background = imgKey;
                btn_Remote_Key_8.Background = imgKey;
                btn_Remote_Key_9.Background = imgKey;


                btn_Remote_Key_Caps.Background = imgCaps;


                lbl_Settings_XBMCIp.Content = _lang.GetString("5", "IP Address :");
                lbl_Settings_XBMCLogin.Content = _lang.GetString("6", "Login :");
                lbl_Settings_XBMCPort.Content = _lang.GetString("7", "Port :");
                lbl_Settings_XBMCPassword.Content = _lang.GetString("8", "Password :");
                lbl_Settings_ImageDir.Content = _lang.GetString("12", "Image directory :");
                lbl_Settings_XBMCMac.Content = _lang.GetString("38", "MAC Address");

                txb_Settings_YATSEHeader.Text = _lang.GetString("9", "YATSE");
                txb_Settings_Resolution.Text = _lang.GetString("10", "Resolution :");
                txb_Settings_ScreenSaverHeader.Text = _lang.GetString("11", "Screen Saver");
                txb_Settings_XBMCHeader.Text = _lang.GetString("13", "XBMC");
                txb_Settings_AboutHeader.Text = _lang.GetString("14", "About");
                txb_Settings_Language.Text = _lang.GetString("25", "Language :");
                txb_Settings_Skin.Text = _lang.GetString("26", "Skin :");
                txb_Current_Nothing.Text = _lang.GetString("27", "Nothing");
                txb_Actions_Close.Text = _lang.GetString("35", "Close YATSE");
                txb_Actions_Settings.Text = _lang.GetString("34", "Parameters");

                txb_Actions_Reboot_Local.Text = _lang.GetString("36", "Reboot Local Computer");
                txb_Actions_Reboot_XBMC.Text = _lang.GetString("40", "Reboot XBMC Computer");
                txb_Actions_Shutdown_Local.Text = _lang.GetString("37", "Shutdown Local Computer");
                txb_Actions_Shutdown_XBMC.Text = _lang.GetString("41", "Shutdown XBMC Computer");
                txb_Actions_WOL_XBMC.Text = _lang.GetString("42", "Wake XBMC Computer");
                txb_NotConnected.Text = _lang.GetString("50", "Not connected to XBMC");

                btn_Settings_SaveSettings.Content = _lang.GetString("15", "Save Settings");
                btn_Settings_SelectImagesDirectory.Content = _lang.GetString("16", "Select Directory");
                btn_Settings_XBMCTest.Content = _lang.GetString("17", "Test");
                btn_Settings_ResfrehLibrary.Content = _lang.GetString("28", "Refresh Library");
                btn_Settings_GetMac.Content = _lang.GetString("39", "Get from IP");


                chk_Settings_Currently.Content = _lang.GetString("18", "Use currently playing when listening music");
                chk_Settings_CurrentlyMovie.Content = _lang.GetString("48", "Use currently playing when watching movie / tv show");
                chk_Settings_Diaporama.Content = _lang.GetString("19", "Use diaporama");
                chk_Settings_Dimming.Content = _lang.GetString("20", "Use dimming when watching movies or no diaporama");
                chk_Settings_ForceResolution.Content = _lang.GetString("21", "Force screen resolution to match YATSE");
                chk_Settings_KeepFocus.Content = _lang.GetString("22", "Keep focus to XBMC");
                chk_Settings_SecondScreen.Content = _lang.GetString("23", "Open Yatse on Secondary Screen");
                chk_Settings_Topmost.Content = _lang.GetString("24", "Keep YATSE topmost");
                chk_Settings_HideCursor.Content = _lang.GetString("32", "Hide mouse cursor");
                chk_Settings_UseBanner.Content = _lang.GetString("46", "Use banner for TV Show");
                chk_Settings_ShowOverlay.Content = _lang.GetString("45", "Show watched Overlay");
                chk_Settings_ShowEmptyMusicGenre.Content = _lang.GetString("47", "Show empty music Genre");
                chk_Settings_ManualRefresh.Content = _lang.GetString("49", "Disable automatic library refresh");
                chk_Settings_ShowScrollBars.Content = _lang.GetString("51", "Show ScrollBars");
                chk_Settings_DisableAnimations.Content = _lang.GetString("52", "Disable Panels Animations");
                
            }
            catch (Exception)
            {
                MessageBox.Show("Error loading Skin !");
                WriteToLog("Error loading Skin !!");
                Application.Exit();
            }
        }

        private static void GiveXbmcFocus()
        {
            var processes = Process.GetProcessesByName("XBMC");
            foreach (var pFoundWindow in processes.Select(p => p.MainWindowHandle))
            {
                SetForegroundWindow(pFoundWindow);
            }
        }

        private void ResetTimer()
        {
            if (_config.KeepFocus)
            {
                GiveXbmcFocus();
            }
            _timer = 0;
        }

        private string GetRandomFile(string path)
        {
            try
            {
                var extensions = new[] { ".png", ".jpg", ".gif", ".jpeg", ".bmp" };

                var di = new DirectoryInfo(path);
                return (di.GetFiles("*.*")
                                    .Where(f => extensions.Contains(f.Extension.ToLower()))
                                    .OrderBy(f => Guid.NewGuid())
                                    .First()).FullName;
            }
            catch { return Application.StartupPath + @"\Skin\" + _currentSkin + @"\Interface\Default_Diaporama.png"; }
        }

        private void RefreshLibrary(bool force)
        {
            if (!_xbmc.Status.IsConnected()) return;
            if (_config.ManualRefresh && !force) return;
            WriteToLog("Start refresh lib");
            grd_Library.Visibility = Visibility.Visible;
            RefreshFilms();
            RefreshMusicGenres();
            RefreshAlbums(null);
            RefreshShows();
            RefreshEpisodes(null);
            grd_Library.Visibility = Visibility.Hidden;
            WriteToLog("End refresh lib");
        }

        private void TimerTick(object sender, EventArgs e)
        {
            _timer += 1;
            _xbmc.Status.Refresh();
            if (_xbmc.Status.IsConnected())
            {
                if (grd_NotConnected.Visibility == Visibility.Visible)
                    grd_NotConnected.Visibility = Visibility.Hidden;
            }
            else
            {
                if (grd_NotConnected.Visibility == Visibility.Hidden)
                    grd_NotConnected.Visibility = Visibility.Visible;
            }

            if (!_isLibraryRefresh)
            {
                if (_xbmc.Status.IsConnected())
                {
                    RefreshLibrary(false);
                    if (!_config.ManualRefresh)
                    {
                        _isLibraryRefresh = true;
                        ShowGrid(grd_Video);
                    }
                }
                if (_config.ShowScrollBars)
                {
                    var sc = FindVisualChild<ScrollViewer>(lst_Video);
                    sc.HorizontalScrollBarVisibility = ScrollBarVisibility.Auto;
                    sc = FindVisualChild<ScrollViewer>(lst_TvEpisode);
                    sc.HorizontalScrollBarVisibility = ScrollBarVisibility.Auto;
                    sc = FindVisualChild<ScrollViewer>(lst_TvShow);
                    sc.HorizontalScrollBarVisibility = ScrollBarVisibility.Auto;
                }
                else
                {
                    var sc = FindVisualChild<ScrollViewer>(lst_Video);
                    sc.HorizontalScrollBarVisibility = ScrollBarVisibility.Hidden;
                    sc = FindVisualChild<ScrollViewer>(lst_TvEpisode);
                    sc.HorizontalScrollBarVisibility = ScrollBarVisibility.Hidden;
                    sc = FindVisualChild<ScrollViewer>(lst_TvShow);
                    sc.HorizontalScrollBarVisibility = ScrollBarVisibility.Hidden;
                }
            }
            
            if (!_xbmc.Status.IsMuted())
            {
                prg_Volume.Value = _xbmc.Status.GetVolume();
            }
            if (_xbmc.Status.IsPlaying() || _xbmc.Status.IsPaused())
            {
                if (_xbmc.Status.IsPaused())
                {
                    btn_Current_Pause.Visibility = Visibility.Hidden;
                    btn_Current_Play.Visibility = Visibility.Visible;
                }
                else
                {
                    btn_Current_Pause.Visibility = Visibility.Visible;
                    btn_Current_Play.Visibility = Visibility.Hidden;
                }
                txt_Current_Time.Text = "" + _xbmc.NowPlaying.Get("time");
                txt_Current_Duration.Text = "" + _xbmc.NowPlaying.Get("duration");
                prg_Current_Progress.Value = _xbmc.Status.GetProgress();
                switch (_xbmc.NowPlaying.GetMediaType())
                {
                    case "Audio":
                        _currentlyPlaying = 2;
                        if (_xbmc.Status.IsNewMediaPlaying())
                        {
                            txt_Current_Music_Song.Text = _xbmc.NowPlaying.Get("track") + ") " + _xbmc.NowPlaying.Get("title");
                            txt_Current_Music_SongDetail.Text = "( " + _xbmc.NowPlaying.Get("bitrate") + "bits " + _xbmc.NowPlaying.Get("samplerate") + "Hz )";
                            txt_Current_Music_Artist.Text = "" + _xbmc.NowPlaying.Get("artist");
                            txt_Current_Music_Album.Text = "" + _xbmc.NowPlaying.Get("album");
                            txt_Current_Music_Genre.Text = "" + _xbmc.NowPlaying.Get("genre");
                            txt_Current_Music_Year.Text = "" + _xbmc.NowPlaying.Get("year");
                            var thumb = _xbmc.NowPlaying.Get("thumb");

                            var thumbparts = thumb.Split('/');
                            thumb = thumbparts[thumbparts.Length - 1];
                            var hash = thumb.Replace(".tbn", "");
                            string cover;
                            if (!File.Exists(Application.StartupPath + @"\Cache\Music\Thumbs\" + hash + ".jpg"))
                            {
                                if (_xbmc.Video.DownloadMusicThumb(hash, Application.StartupPath + @"\Cache\Music\Thumbs\" + hash + ".jpg"))
                                {
                                    cover = Application.StartupPath + @"\Cache\Music\Thumbs\" + hash + ".jpg";
                                }
                                else
                                {
                                    cover = Application.StartupPath + @"\Skin\" + _currentSkin + @"\Interface\Default_MusicThumb.jpg";
                                }
                            }
                            else
                            {
                                cover = Application.StartupPath + @"\Cache\Music\Thumbs\" + hash + ".jpg";
                            }
                            var myBrush = new ImageBrush { ImageSource = new BitmapImage(new Uri(cover, UriKind.Relative)) };

                            img_Current_Music_Image.Fill = myBrush;
                            if (_config.Currently)
                            {
                                _timer = TimerScreenSaver + 1;
                            }
                        }
                        grd_Current_Video.Visibility = Visibility.Hidden;
                        grd_Current_Playbar.Visibility = Visibility.Visible;
                        grd_Current_None.Visibility = Visibility.Hidden;
                        grd_Current_Music.Visibility = Visibility.Visible;
                        grd_Current_Show.Visibility = Visibility.Hidden;
                        if (_config.Currently && grd_Current.Visibility != Visibility.Visible)
                        {
                            _isScreenSaver = false;
                            if (grd_Dimming.Visibility == Visibility.Visible)
                            {
                                grd_Dimming_MouseDown(null, null);
                            }
                            if (grd_Diaporama.Visibility == Visibility.Visible)
                            {
                                grd_Diaporama_MouseDown(null, null);
                            }
                        }
                        break;
                    case "Video":
                        _currentlyPlaying = 1;
                        if (_xbmc.Status.IsNewMediaPlaying())
                        {
                            txt_Current_Video_Title.Text = _xbmc.NowPlaying.Get("title");
                            txt_Current_Show_Title.Text = _xbmc.NowPlaying.Get("showtitle") + " (S"+ _xbmc.NowPlaying.Get("season") + " / E" +_xbmc.NowPlaying.Get("episode") + ") : " +_xbmc.NowPlaying.Get("title");
                            txt_Current_Video_Director.Text = _lang.GetString("4","Director : ") + _xbmc.NowPlaying.Get("director");
                            txt_Current_Video_Genre.Text = "" + _xbmc.NowPlaying.Get("genre");
                            txt_Current_Video_Plot.Text = "" + _xbmc.NowPlaying.Get("plot");
                            txt_Current_Show_Plot.Text = "" + _xbmc.NowPlaying.Get("plot");
                            txt_Current_Video_Tagline.Text = "" + _xbmc.NowPlaying.Get("tagline");
                            txt_Current_Video_Year.Text = "" + _xbmc.NowPlaying.Get("year");
                            var filename = _xbmc.NowPlaying.Get("filename");
                            if (filename.StartsWith("stack://"))
                            {
                                var spliter = new string[1];
                                spliter[0] = " , ";
                                var temp = filename.Split(spliter, StringSplitOptions.None);
                                filename = temp[0].Replace("stack://", "");
                            }

                            var hash = XbmcVideo.Hash(filename);
                            string cover;
                            if (!File.Exists(Application.StartupPath + @"\Cache\Video\Thumbs\" + hash + ".jpg"))
                            {
                                if (_xbmc.Video.DownloadThumb(hash, Application.StartupPath + @"\Cache\Video\Thumbs\" + hash + ".jpg"))
                                {
                                    cover = Application.StartupPath + @"\Cache\Video\Thumbs\" + hash + ".jpg";
                                }
                                else
                                {
                                    cover = Application.StartupPath + @"\Skin\" + _currentSkin + @"\Interface\Default_Thumb.jpg";
                                }
                            }
                            else
                            {
                                cover = Application.StartupPath + @"\Cache\Video\Thumbs\" + hash + ".jpg";
                            }
                            var myBrush = new ImageBrush { ImageSource = new BitmapImage(new Uri(cover, UriKind.Relative)) };

                            img_Current_Video_Image.Fill = myBrush;
                            img_Current_Show_Image.Fill = myBrush;
                            if (_config.Dimming)
                            {
                                _timer = TimerScreenSaver + 1;
                            }
                            if (_config.CurrentlyMovie && grd_Current.Visibility != Visibility.Visible)
                            {
                                _isScreenSaver = false;
                                if (grd_Dimming.Visibility == Visibility.Visible)
                                {
                                    grd_Dimming_MouseDown(null, null);
                                }
                                if (grd_Diaporama.Visibility == Visibility.Visible)
                                {
                                    grd_Diaporama_MouseDown(null, null);
                                }
                            }
                            if (_config.CurrentlyMovie)
                            {
                                _timer = TimerScreenSaver + 1;
                            }
                        }
                        if (_xbmc.NowPlaying.Get("showtitle") == null)
                        {
                            grd_Current_Video.Visibility = Visibility.Visible;
                            grd_Current_Show.Visibility = Visibility.Hidden;
                        }
                        else
                        {
                            grd_Current_Video.Visibility = Visibility.Hidden;
                            grd_Current_Show.Visibility = Visibility.Visible;
                        }

                        grd_Current_Playbar.Visibility = Visibility.Visible;
                        grd_Current_None.Visibility = Visibility.Hidden;
                        grd_Current_Music.Visibility = Visibility.Hidden;

                        if (_config.Dimming && grd_Dimming.Visibility != Visibility.Visible)
                        {
                            _isScreenSaver = false;
                            if (grd_Diaporama.Visibility == Visibility.Visible)
                            {
                                grd_Diaporama_MouseDown(null, null);
                            }
                        }
                        break;
                    default:
                        grd_Current_Video.Visibility = Visibility.Hidden;
                        grd_Current_Playbar.Visibility = Visibility.Hidden;
                        grd_Current_None.Visibility = Visibility.Visible;
                        grd_Current_Music.Visibility = Visibility.Hidden;
                        grd_Current_Show.Visibility = Visibility.Hidden;
                        _currentlyPlaying = 0;
                        break;
                }
            }
            else
            {
                grd_Current_Video.Visibility = Visibility.Hidden;
                grd_Current_Playbar.Visibility = Visibility.Hidden;
                grd_Current_None.Visibility = Visibility.Visible;
                grd_Current_Music.Visibility = Visibility.Hidden;
                grd_Current_Show.Visibility = Visibility.Hidden;
                _currentlyPlaying = 0;
            }

            // Start correct ScreenSaver
            if (_timer > TimerScreenSaver)
            {
                if (!_isScreenSaver)
                {
                    _isScreenSaver = true;
                    if (_config.Dimming
                        && (!_config.Diaporama || _currentlyPlaying == 1)
                        && !(_config.Currently && _currentlyPlaying == 2)
                        && !(_config.CurrentlyMovie && _currentlyPlaying == 1)
                        )
                    {
                        var stbDimmingShow = (Storyboard)TryFindResource("stb_ShowDimming");
                        stbDimmingShow.Begin(this);
                    }
                    if (_config.Diaporama
                        && !(_config.Dimming && _currentlyPlaying == 1)
                        && !(_config.Currently && _currentlyPlaying == 2)
                        && !(_config.CurrentlyMovie && _currentlyPlaying == 1)
                        )
                    {
                        img_Diaporama1.Source = new BitmapImage(new Uri(GetRandomFile(_config.ImageDirectory)));
                        _diaporamaCurrentImage = 1;
                        var stbDiaporamaShow = (Storyboard)TryFindResource("stb_ShowDiaporama");
                        stbDiaporamaShow.Begin(this);
                        var stbDiaporamaSwap = (Storyboard)TryFindResource("stb_Diaporama_12_1");
                        stbDiaporamaSwap.Begin(this);
                    }
                    if (   (_config.Currently && _currentlyPlaying == 2 )
                        || (!_config.Diaporama && !_config.Dimming)
                        || (_config.CurrentlyMovie && _currentlyPlaying ==1)
                        )
                    {
                        ShowGrid(grd_Current);
                    }
                }
                ResetTimer();
            }

            // Diaporama Image Rotation
            if (_isScreenSaver && _diaporamaCurrentImage != 0 && (_timer % 5) == 0)
            {
                if (_diaporamaCurrentImage == 1)
                {
                    _diaporamaCurrentImage = 2;
                    img_Diaporama2.Source = new BitmapImage(new Uri(GetRandomFile(_config.ImageDirectory)));
                    var stbDiaporamaSwap = (Storyboard)TryFindResource("stb_Diaporama_12_1");
                    stbDiaporamaSwap.Begin(this);
                }
                else
                {
                    _diaporamaCurrentImage = 1;
                    img_Diaporama1.Source = new BitmapImage(new Uri(GetRandomFile(_config.ImageDirectory)));
                    var stbDiaporamaSwap = (Storyboard)TryFindResource("stb_Diaporama_21_1");
                    stbDiaporamaSwap.Begin(this);
                }
            }

            // Check if we are on the correct screen if not move
            var screens = Screen.AllScreens;
            var dx = 1.0;
            var dy = 1.0;
            if (PresentationSource.FromVisual(this) != null)
            {
                var m = PresentationSource.FromVisual(this).CompositionTarget.TransformToDevice;
                dx = m.M11;
                dy = m.M22;
            }
            if (screens.Length == 1 || !_config.SecondScreen)
            {
                if (Top != 0 || Left != 0)
                {
                    Top = 0;
                    Left = 0;
                }
            }
            else
            {
                foreach (var scr in
                    screens.Where(scr => !scr.Primary).Where(scr => Top != (scr.Bounds.Top / dy) || Left != (scr.Bounds.Left / dx)))
                {
                    Top = scr.Bounds.Top / dy;
                    Left = scr.Bounds.Left / dx;
                    break;
                }
            }

            if (!_config.IsConfigured)
            {
                btn_Actions_Settings_Click(null,null);
            }

        }

        private void InitXbmc()
        {
            if (_xbmc == null)
                _xbmc = new XbmcCommunicator();
            if (_config.XBMCIp == "") return;
            _xbmc.SetCredentials(_config.XBMCLogin, _config.XBMCPassword);
            _xbmc.SetIp(_config.XBMCIp + ":" + _config.XBMCPort);
            _xbmc.DebugEnabled = _config.Debug;
        }

        private string GetVideoThumb(string path, string file)
        {
            var filename = path + file;
            var hash = XbmcVideo.Hash(filename);
            string  thumb;
            if (file.StartsWith("stack://"))
            {
                var spliter = new string[1];
                spliter[0] = " , ";
                var temp = file.Split(spliter, StringSplitOptions.None);
                hash = XbmcVideo.Hash(temp[0].Replace("stack://", ""));
            }

            if (!File.Exists(Application.StartupPath + @"\Cache\Video\Thumbs\" + hash + ".jpg"))
            {
                if (_xbmc.Video.DownloadThumb(hash, Application.StartupPath + @"\Cache\Video\Thumbs\" + hash + ".jpg"))
                {
                    thumb = Application.StartupPath + @"\Cache\Video\Thumbs\" + hash + ".jpg";
                }
                else
                {
                    thumb = Application.StartupPath + @"\Skin\" + _currentSkin + @"\Interface\Default_Thumb.jpg";
                }
            }
            else
            {
                thumb = Application.StartupPath + @"\Cache\Video\Thumbs\" + hash + ".jpg";
            }
            return thumb;
        }

        private string GetVideoFanart(string path, string file)
        {
            var filename = path + file;
            var hash = XbmcVideo.Hash(filename);
            string fanart;
            if (file.StartsWith("stack://"))
            {
                hash = XbmcVideo.Hash(file);
            }

            if (!File.Exists(Application.StartupPath + @"\Cache\Video\Fanarts\" + hash + ".jpg"))
            {
                if (_xbmc.Video.DownloadFanart(hash, Application.StartupPath + @"\Cache\Video\Fanarts\" + hash + ".jpg"))
                {
                    fanart = Application.StartupPath + @"\Cache\Video\Fanarts\" + hash + ".jpg";
                }
                else
                {
                    fanart = Application.StartupPath + @"\Skin\" + _currentSkin + @"\Interface\Default_Fanart.jpg";
                }
            }
            else
            {
                fanart = Application.StartupPath + @"\Cache\Video\Fanarts\" + hash + ".jpg";
            }
            return fanart;
        }


        private void RefreshMusicGenres()
        {
            if (_genreDataSource == null) return;

            _genreDataSource.Clear();
            string req;
            if (_config.ShowEmptyMusicGenre)
            {
                req = "SELECT idGenre, strGenre FROM genre ORDER BY strGenre"; 
            }
            else
            {
                req = "SELECT idGenre,strGenre FROM albumview GROUP BY strGenre ORDER BY strGenre";   
            }
            var genres = _xbmc.MultiMusicRequest(req);
            if (genres == null) return;
            var numgenres = genres.Length;
            txb_Library_Title.Text = _lang.GetString("31", "Genres");
            prg_Library_Refresh.Value = 0;
            var index = 0.0;

            foreach (var temp in genres)
            {
                if (temp.Count() < 2) continue;
                if (grd_Library.Visibility == Visibility.Visible)
                {
                    txb_Library_File.Text = temp[1];
                    index += Math.Min(100.0, 100.0 / numgenres);
                    prg_Library_Refresh.Value = index;
                    if ((int)index % 5 == 0)
                        Application.DoEvents();
                }
                var uri = Application.StartupPath + @"\Skin\" + _currentSkin + @"\Music_Genre\" + temp[1] + ".jpg";
                if (!File.Exists(uri))
                {
                    uri = Application.StartupPath + @"\Skin\" + _currentSkin + @"\Music_Genre\Default.png";
                }
                var genre = new MusicGenre { Cover = uri, Id = temp[0], Name = temp[1] };
                _genreDataSource.Add(genre);
            }
            SelectGenre(0);
        }

        private void RefreshAlbums(string idGenre)
        {
            if (_albumDataSource == null) return;
            _albumDataSource.Clear();
            txt_Album_Title.Text = _lang.GetString("33", "No Medias");
            string req;
            if (idGenre == null)
            {
                req = "SELECT idAlbum,strAlbum,idGenre,strArtist,strGenre,iYear,strThumb FROM albumview GROUP BY strAlbum ORDER BY strAlbum";
            }
            else
            {
                req = "SELECT idAlbum,strAlbum,idGenre,strArtist,strGenre,iYear,strThumb FROM albumview WHERE idGenre = " + idGenre + " GROUP BY strAlbum ORDER BY strAlbum";
            }

            var albums = _xbmc.MultiMusicRequest(req);
            if (albums == null) return;
            var numalbums = albums.Length;
            txb_Library_Title.Text = _lang.GetString("29", "Albums");
            prg_Library_Refresh.Value = 0;
            var index = 0.0;
            
            foreach (var album in albums)
            {
                if (album.Count() < 7) continue;
                if (grd_Library.Visibility == Visibility.Visible)
                {
                    txb_Library_File.Text = album[1];
                    index += Math.Min(100.0, 100.0 / numalbums);
                    prg_Library_Refresh.Value = index;
                    if ((int)index % 10 == 0)
                        Application.DoEvents();
                }
                var oneAlbum = new MusicAlbum
                                   {
                                       IdAlbum = album[0],
                                       Title = album[1],
                                       IdGenre = album[2],
                                       Artist = album[3],
                                       Genre = album[4],
                                       Year = album[5]
                                   };
                var thumb = album[6];
                var thumbparts = thumb.Split('/');
                thumb = thumbparts[thumbparts.Length - 1];
                var hash = thumb.Replace(".tbn", "");
                if (!File.Exists(Application.StartupPath + @"\Cache\Music\Thumbs\" + hash + ".jpg"))
                {
                    if (_xbmc.Video.DownloadMusicThumb(hash, Application.StartupPath + @"\Cache\Music\Thumbs\" + hash + ".jpg"))
                    {
                        oneAlbum.Cover = Application.StartupPath + @"\Cache\Music\Thumbs\" + hash + ".jpg";
                    }
                    else
                    {
                        oneAlbum.Cover = Application.StartupPath + @"\Skin\" + _currentSkin + @"\Interface\Default_MusicThumb.jpg";
                    }
                }
                else
                {
                    oneAlbum.Cover = Application.StartupPath + @"\Cache\Music\Thumbs\" + hash + ".jpg";
                }
                _albumDataSource.Add(oneAlbum);
            }

            SelectAlbum(0);
        }

        private void RefreshShows()
        {
            if (_showDataSource == null) return;
            _showDataSource.Clear();
            txt_TvShow_Title.Text = _lang.GetString("33", "No Medias");
            var shows = _xbmc.MultiVideoRequest("SELECT idShow,c00,c01,c05,c08,c13,c14,strPath,totalCount FROM tvshowview ORDER BY c00");
            if (shows == null) return;
            var numshows = shows.Length;
            txb_Library_Title.Text = _lang.GetString("43", "TV Show");
            prg_Library_Refresh.Value = 0;
            var index = 0.0;
            foreach (var show in shows)
            {
                if (show.Count()<9) continue;
                if (grd_Library.Visibility == Visibility.Visible)
                {
                    txb_Library_File.Text = show[1];
                    index += Math.Min(100.0, 100.0 / numshows);
                    prg_Library_Refresh.Value = index;
                    if ((int)index % 5 == 0)
                        Application.DoEvents();
                }
                show[3] = show[3].Split('-')[0];
                var oneShow = new TvShow
                                  {
                                      IdShow = show[0],
                                      Title = show[1],
                                      Plot = show[2],
                                      Date = show[3],
                                      Genre = show[4],
                                      MPAA = show[5],
                                      Studio = show[6],
                                      DirName = show[7],
                                      TotalCount = show[8],
                                      Hash = XbmcVideo.Hash(show[7])
                                  };

                oneShow.Cover = GetVideoThumb(oneShow.DirName, "");
                oneShow.Fanart = GetVideoFanart(oneShow.DirName, "");
                
                _showDataSource.Add(oneShow);
            }
            lst_TvShow.SelectedItems.Clear();
            lst_TvShow.SelectedIndex = 0;
            if (lst_TvShow.Items.Count > 0) 
                lst_TvShow.ScrollIntoView(lst_TvShow.Items.GetItemAt(0));
        }

        private void RefreshEpisodes(string idshow)
        {
            if (_episodeDataSource == null) return;
            _episodeDataSource.Clear();
            txt_TvEpisode_Title.Text = _lang.GetString("33", "No Medias");
            string req;
            if (idshow == null)
                req = "SELECT idEpisode,c00,c01,c05,c12,c13,strFileName,strPath,playCount,strTitle,strStudio,idShow FROM episodeview ORDER BY CAST(c12 AS INTEGER) DESC ,CAST(c13 AS INTEGER)";
            else
                req = "SELECT idEpisode,c00,c01,c05,c12,c13,strFileName,strPath,playCount,strTitle,strStudio,idShow FROM episodeview WHERE idShow = " + idshow + " ORDER BY CAST(c12 AS INTEGER) DESC ,CAST(c13 AS INTEGER)";

            var episodes = _xbmc.MultiVideoRequest(req);
            if (episodes == null) return;
            var numsepisodes = episodes.Length;
            txb_Library_Title.Text = _lang.GetString("44", "TV Episodes");
            prg_Library_Refresh.Value = 0;
            var index = 0.0;
            foreach (var episode in episodes)
            {
                if (episode.Count() < 10) continue;
                if (grd_Library.Visibility == Visibility.Visible)
                {
                    txb_Library_File.Text = episode[9] + " / " + episode[1];
                    index += Math.Min(100.0, 100.0 / numsepisodes);
                    prg_Library_Refresh.Value = index;
                    if ((int)index % 10 == 0)
                        Application.DoEvents();
                }

                var oneEpisode = new TvEpisode
                {
                    IdEpisode = episode[0],
                    Title = episode[1],
                    Plot = episode[2],
                    Date = episode[3].Split('-')[0],
                    Season = episode[4],
                    Episode = episode[5],
                    FileName = episode[6],
                    DirName = episode[7],
                    PlayCount = episode[8],
                    ShowTitle = episode[9],
                    Studio = episode[10],
                    //MPAA = episode[11],
                    Hash = XbmcVideo.Hash(episode[7] + episode[8])
                };

                foreach (var show in _showDataSource)
                {
                    if (show.IdShow == episode[11] )
                    {
                        oneEpisode.Fanart = show.Fanart;
                        break;
                    }

                }
                oneEpisode.Cover = GetVideoThumb(oneEpisode.DirName, oneEpisode.FileName);
                if (! _config.ShowOverlay)
                {
                    oneEpisode.PlayCount = "0";
                }
                if (oneEpisode.PlayCount == "") 
                    oneEpisode.PlayCount = "0";
                oneEpisode.Seen = Convert.ToInt32(oneEpisode.PlayCount, 10) >= 1
                                          ? Visibility.Visible
                                          : Visibility.Hidden;
                
                oneEpisode.WatchedImage = Application.StartupPath + @"\Skin\" + _currentSkin + @"\Interface\Watched.png";

                _episodeDataSource.Add(oneEpisode);
            }
            lst_TvEpisode.SelectedItems.Clear();
            lst_TvEpisode.SelectedIndex = 0;
            if (lst_TvEpisode.Items.Count > 0) 
                lst_TvEpisode.ScrollIntoView(lst_TvEpisode.Items.GetItemAt(0));
        }

        private void RefreshFilms()
        {
            if (_filmDataSource == null) return;
            _filmDataSource.Clear();

            var films = _xbmc.MultiVideoRequest("SELECT c00,c01,c03,c05,c07,c11,c14,c15,idFile,idMovie,strFileName,strPath,playCount FROM movieview ORDER BY c00");
            if (films == null) return;
            var numfilms = films.Length;
            txb_Library_Title.Text = _lang.GetString("30", "Movies");
            prg_Library_Refresh.Value = 0;
            var index = 0.0;
            foreach (var film in films)
            {
                if (film.Count() < 13) continue;
                if (grd_Library.Visibility == Visibility.Visible)
                {
                    txb_Library_File.Text = film[0];
                    index += Math.Min(100.0, 100.0 / numfilms);
                    prg_Library_Refresh.Value = index;
                    if ((int)index % 10 == 0)
                        Application.DoEvents();
                }

                if (film[10].StartsWith("stack://"))
                {
                    film[11] = "";
                }

                var oneFilm = new Film
                                  {
                                      Title = film[0],
                                      Plot = film[1],
                                      Tagline = film[2],
                                      Rating = film[3],
                                      Year = film[4],
                                      Duration = film[5],
                                      Genre = film[6],
                                      Director = film[7],
                                      IdFile = film[8],
                                      IdMovie = film[9],
                                      FileName = film[10],
                                      DirName = film[11],
                                      PlayCount = film[12],
                                      Hash = XbmcVideo.Hash(film[11] + film[10])
                                  };

                if (!_config.ShowOverlay)
                {
                    oneFilm.PlayCount = "0";
                }

                if (oneFilm.PlayCount == "") oneFilm.PlayCount = "0";
                oneFilm.Seen = Convert.ToInt32(oneFilm.PlayCount,10) >= 1 ? Visibility.Visible : Visibility.Hidden;
                oneFilm.WatchedImage = Application.StartupPath + @"\Skin\" + _currentSkin + @"\Interface\Watched.png";
                oneFilm.Cover = GetVideoThumb(oneFilm.DirName, oneFilm.FileName);
                oneFilm.Fanart = GetVideoFanart(oneFilm.DirName, oneFilm.FileName);
                _filmDataSource.Add(oneFilm);
            }
            lst_Video.SelectedItems.Clear();
            lst_Video.SelectedIndex = 0;
            lst_Video.ScrollIntoView(lst_Video.Items.GetItemAt(0));
        }

        private void SelectAlbum(int index)
        {
            if (index < 0) return;
            if (index >= lst_Albums.Items.Count) return;
            var albumsFlow = FindChild<VirtElementFlow>(lst_Albums, "ElementFlow");
            lst_Albums.SelectedIndex = index;
            lst_Albums.ScrollIntoView(lst_Albums.Items.GetItemAt(index));
            albumsFlow.StoredSelectedIndex = -1;
            albumsFlow.SelectedIndex = index;

        }

        private void SelectGenre(int index)
        {
            if (index < 0) return;
            if (index >= lst_MusicGenre.Items.Count) return;
            var genresFlow = FindChild<VirtElementFlow>(lst_MusicGenre, "ElementFlow");
            genresFlow.StoredSelectedIndex = -1;
            genresFlow.SelectedIndex = index;
            lst_MusicGenre.SelectedIndex = index;
            lst_MusicGenre.ScrollIntoView(lst_MusicGenre.Items.GetItemAt(index));
        }

        private static T FindChild<T>(DependencyObject parent, string childName)
           where T : DependencyObject
        {
            if (parent == null) return null;
            T foundChild = null;
            var childrenCount = VisualTreeHelper.GetChildrenCount(parent);
            for (var i = 0; i < childrenCount; i++)
            {
                var child = VisualTreeHelper.GetChild(parent, i);
                var childType = child as T;
                if (childType == null)
                {
                    foundChild = FindChild<T>(child, childName);
                    if (foundChild != null) break;
                }
                else if (!string.IsNullOrEmpty(childName))
                {
                    var frameworkElement = child as FrameworkElement;
                    if (frameworkElement != null && frameworkElement.Name == childName)
                    {
                        foundChild = (T)child;
                        break;
                    }
                }
                else
                {
                    foundChild = (T)child;
                    break;
                }
            }
            return foundChild;
        }
        public YatseWindow()
        {
            InitializeComponent();

            _config.HideCursor = false;
            _config.Currently = true;
            _config.CurrentlyMovie = false;
            _config.Diaporama = false;
            _config.Dimming = true;
            _config.ForceResolution = false;
            _config.IsConfigured = false;
            _config.KeepFocus = true;
            _config.Language = "English";
            _config.SecondScreen = true;
            _config.Skin = "Default";
            _config.ShowOverlay = true;
            _config.UseBanner = false;
            _config.ShowEmptyMusicGenre = false;
            _config.ShowScrollBars = false;
            _config.TopMost = true;
            _config.ManualRefresh = false;
            _config.XBMCIp = "127.0.0.1";
            _config.XBMCPort = "80";
            _config.XBMCLogin = "xbmc";
            _config.XBMCPassword = "xbmc";
            _config.DisableAnimations = false;
            LoadConfig(_configFile);

            RotateLog();
            WriteToLog("----- Starting YATSE -----");

            if (_config.HideCursor)
                Cursor = System.Windows.Input.Cursors.None;

            if (File.Exists(Application.StartupPath + @"\Langs\" + _config.Language +".xml"))
            {
                _lang.LoadXml(Application.StartupPath + @"\Langs\" + _config.Language + ".xml");
            }
            else
            {
                _lang.LoadXml(Application.StartupPath + @"\Langs\English.xml");
            }
            if (Directory.Exists(Application.StartupPath + @"\Skin\" + _config.Skin))
            {
                _currentSkin = _config.Skin;
            }

            LoadSkin();

            SystemEvents.DisplaySettingsChanged += Change_Display_Settings;

            var dispatchTimer = new DispatcherTimer();
            dispatchTimer.Tick += TimerTick;
            dispatchTimer.Interval = new TimeSpan(0, 0, 1);
            dispatchTimer.Start();

            _currentGrid = grd_Remote;
            
            InitXbmc();

            Directory.CreateDirectory(Application.StartupPath + @"\Log");
            Directory.CreateDirectory(Application.StartupPath + @"\Cache");
            Directory.CreateDirectory(Application.StartupPath + @"\Cache\Video");
            Directory.CreateDirectory(Application.StartupPath + @"\Cache\Music");
            Directory.CreateDirectory(Application.StartupPath + @"\Cache\Video\Thumbs");
            Directory.CreateDirectory(Application.StartupPath + @"\Cache\Video\Fanarts");
            Directory.CreateDirectory(Application.StartupPath + @"\Cache\Music\Thumbs");
            Directory.CreateDirectory(Application.StartupPath + @"\Cache\Music\Fanarts");

            _genreDataSource = TryFindResource("GenresDataSource") as GenreCollection;
            _filmDataSource = TryFindResource("FilmsDataSource") as FilmCollection;
            _albumDataSource = TryFindResource("AlbumsDataSource") as AlbumCollection;
            _showDataSource = TryFindResource("ShowsDataSource") as ShowCollection;
            _episodeDataSource = TryFindResource("EpisodesDataSource") as EpisodeCollection;

            var transition = TryFindResource("SlideTransition") as SlideTransition;
            if (transition != null)
                transition.Direction = Direction.RightToLeft;
            WriteToLog("End init");
        }

        private void ShowGrid(Grid newGrid)
        {
            ResetTimer();
            _isScreenSaver = false;
            if (_currentGrid.Name == newGrid.Name) return;
            if (trp_Transition.IsTransitioning) return;
            if (!_config.DisableAnimations)
            {
                trp_Transition.ApplyTransition(_currentGrid.Name, newGrid.Name);
            }
            else
            {
                _currentGrid.Visibility = Visibility.Hidden;
                newGrid.Visibility = Visibility.Visible;
            }
            _currentGrid = newGrid;
        }


        private void ShowVolume()
        {
            var stbVolume = (Storyboard)TryFindResource("stb_ShowVolume");
            stbVolume.Begin(this);
        }

        private static object GetObjectDataFromPoint(ListBox source, Point point)
        {
            var element = source.InputHitTest(point) as UIElement;
            if (element != null)
            {
                if (element is ListBoxItem)
                    return element;
                while (element != source)
                {
                    if (element != null) element = VisualTreeHelper.GetParent(element) as UIElement;
                    if (element is ListBoxItem)
                        return element;
                }
            }
            return null;
        }

        private static TChildItem FindVisualChild<TChildItem>(DependencyObject obj)
   where TChildItem : DependencyObject
        {
            for (var i = 0; i < VisualTreeHelper.GetChildrenCount(obj); i++)
            {
                var child = VisualTreeHelper.GetChild(obj, i);
                if (child != null && child is TChildItem)
                    return (TChildItem)child;
                var childOfChild = FindVisualChild<TChildItem>(child);
                if (childOfChild != null)
                    return childOfChild;
            }
            return null;
        }



        private class FakeWindowsPeer : WindowAutomationPeer
        {
            public FakeWindowsPeer(Window window) : base(window)
            { }

            protected override List<AutomationPeer> GetChildrenCore()
            { return null; }

        }

        protected override AutomationPeer OnCreateAutomationPeer()

        { return new FakeWindowsPeer(this); }

    }
}
